/**
 * @Date 2025/2/26 15:11
 * @Created by 衡盛永
 */

package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Employee;
import com.sky.entity.SetmealDish;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishPageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 菜品业务实现类
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        int page = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();
        PageHelper.startPage(page, pageSize);
        List<Dish> dishes = dishMapper.pageQuery(dishPageQueryDTO);
        ArrayList<DishPageVO> dishPageVOArrayList = new ArrayList<>();
        for (Dish dish : dishes) {
            DishPageVO dishPageVO = new DishPageVO();
            BeanUtils.copyProperties(dish, dishPageVO);
            dishPageVOArrayList.add(dishPageVO);
        }
        PageInfo<DishPageVO> dishPageVOPageInfo = new PageInfo<>(dishPageVOArrayList);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(dishPageVOPageInfo.getTotal());
        pageResult.setRecords(dishPageVOPageInfo.getList());
        return pageResult;
    }

    @Override
    public List<Dish> list(Integer categoryId) {
        return dishMapper.list(categoryId);
    }

    @Override
    @Transactional
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.ENABLE);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.save(dish);
        Long dishId = dish.getId();
        for (DishFlavor dishFlavor : dishDTO.getFlavors()) {
            dishFlavor.setDishId(dishId);
            dishFlavorMapper.save(dishFlavor);
        }
    }
}
